package com.springboot.codeminestarter.codemine.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.codeminestarter.codemine.constant.Constant;
import com.springboot.codeminestarter.codemine.exception.BusinessException;
import com.springboot.codeminestarter.codemine.tips.TipMess;

public class JwtUtil {

    public static <T> T getClaim(String token, String claimKey, Class<T> clazz) {

        Claim claim = null;
        T t = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Constant.SECRET)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            claim = decodedJWT.getClaim(claimKey);
            t = claim.as(clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(TipMess.BASE_TOKEN_CHECK_FAIL);
        }
        return t;
    }

    public static Long getClaimExpireTime(String token) {

        Long time = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Constant.SECRET)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            time = DateUtil.getTime(decodedJWT.getExpiresAt());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(TipMess.BASE_FAIL_TOKEN_LIFESPAN);
        }
        return time;
    }
}
